package vip.sweet.sys.modular.department.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import vip.sweet.sys.modular.department.entity.Department;
import vip.sweet.sys.modular.department.mapper.DepartmentMapper;
import vip.sweet.sys.modular.department.params.AddDepartmentParams;
import vip.sweet.sys.modular.department.service.DepartmentService;
import vip.sweet.sys.modular.department.vo.DepartmentVo;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ASUS
 * @Date 2025/4/8 11:12
 * @Descripition
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {
    @Override
    public boolean add(AddDepartmentParams addDepartmentParams) {
        return save(BeanUtil.copyProperties(addDepartmentParams, Department.class));
    }

    @Override
    public List<DepartmentVo> tree() {
        List<Department> list = list();
        List<DepartmentVo> departmentVOS = list.stream().map(
                department -> {
                    DepartmentVo departmentVO = new DepartmentVo();
                    BeanUtil.copyProperties(department, departmentVO);
                    departmentVO.setKey(department.getId());
                    departmentVO.setTitle(department.getName());
                    return departmentVO;
                }
        ).toList();
        return departmentVOS.stream().filter(departmentVo -> departmentVo.getParentId().equals("TOP")).peek(departmentVo -> departmentVo.setChildren(getChildrenData(departmentVo, departmentVOS))).toList();
    }
    //获取孩子（下级目录）的方法，递归实现
    private List<DepartmentVo> getChildrenData(DepartmentVo root, List<DepartmentVo> all) {
        return all.stream().filter(subjectVO ->
                subjectVO.getParentId().equals(root.getKey())
        ).peek(subjectVO -> subjectVO.setChildren(getChildrenData(subjectVO, all))).collect(Collectors.toList());
    }
}
